import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入登录组件的页面
import Login from '@/views/login'
// 导入用户布局组件的页面
import Userlayout from '@/views/userLayout'
// 导入用户模块的组件的页面
import Userhome from '@/views/userLayout/userHome'
import Houseinfo from '@/views/userLayout/houseInfo'
import Manage from '@/views/userLayout/manage'
import Publish from '@/views/userLayout/publish'
import Collect from '@/views/userLayout/collect'
import Setting from '@/views/userLayout/setting'
import Details from '@/views/userLayout/houseDetails'
// 导入管理员布局组件的页面
import Adminlayout from '@/views/adminLayout'
// 导入管理员模块组件的页面
import Adminhome from '@/views/adminLayout/adminHome'
import Usermanagement from '@/views/adminLayout/userManagement'
import Homemanagement from '@/views/adminLayout/homeManagement'

Vue.use(VueRouter)
// 路由配置项
const routes = [
  // 路由重定向到login
  // { path: '/', redirect: '/login' },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  // 用户模块的路由列表
  {
    path: '/',
    component: Userlayout,
    redirect: '/userhome',
    children: [
      {
        path: '',
        name: 'Userhome',
        component: Userhome
      },
      {
        path: '/houseinfo',
        name: 'Houseinfo',
        component: Houseinfo
      },
      {
        path: '/manage',
        name: 'Manage',
        component: Manage
      },
      {
        path: '/publish',
        name: 'Publish',
        component: Publish
      },
      {
        path: '/collect',
        name: 'Collect',
        component: Collect
      },
      {
        path: '/setting',
        name: 'Setting',
        component: Setting
      },
      {
        path: '/details',
        name: 'Details',
        component: Details
      }
    ]
  },
  // 管理员模块的路由列表
  {
    path: '/admin',
    component: Adminlayout,
    redirect: '/adminhome',
    children: [
      {
        path: '/admin',
        name: 'adminLayout',
        component: Adminhome
      },
      {
        path: '/usermanagement',
        name: 'userManagement',
        component: Usermanagement
      },
      {
        path: '/homemanagement',
        name: 'homemanagement',
        component: Homemanagement
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 路由导航守卫
router.beforeEach((to, from, next) => {
  // 1. to将访问的路径
  // 2. from代表从那个路径跳转而来
  // 3. next是一个函数，表示放行
  // 4. next() 放行 next('/login')  强制登录
  // 获取 token
  const userToken = window.localStorage.getItem('userToken')
  const adminToken = window.localStorage.getItem('adminToken')
  if (to.path !== '/login') {
    if (userToken || adminToken) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
